package com.zzyl.nursing.service.impl;

import java.time.Year;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    private final CheckInMapper checkInMapper;

    private final ElderMapper elderMapper;

    private final BedMapper bedMapper;

    private final CheckInConfigMapper checkInConfigMapper;

    private final ContractMapper contractMapper;


    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo selectCheckInDetailById(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));

        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getId, checkIn.getElderId()));
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        int birthYear = Year.now().getValue() - Integer.parseInt(elder.getIdCardNo().substring(6, 10));
        checkInElderVo.setAge(birthYear);

        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));

        String remark = elder.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(remark)) {
             elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        }

        return CheckInDetailVo.builder().checkInConfigVo(checkInConfigVo).checkInElderVo(checkInElderVo).contract(contract).elderFamilyVoList(elderFamilyVoList).build();
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否已经入住
        Elder elderTemp = elderMapper.selectElderByidCardNo(checkInApplyDto.getCheckInElderDto().getIdCardNo());
        if (!ObjectUtils.isEmpty(elderTemp)) {
            throw new BaseException("该老人已入住，请重新输入");
        }
        //更新对应床位状态
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(Constants.STATUS_ENABLED);
        bedMapper.updateById(bed);
        //判断是否传入家属信息 ==> 家属信息不完整，请输入家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        if (CollectionUtils.isEmpty(elderFamilyDtoList)) {
            throw new BaseException("家属信息不完整，请输入家属信息");
        }
        //构建Elder对象
        CheckInElderDto elderDto = checkInApplyDto.getCheckInElderDto();
        Elder elder = BeanUtil.toBean(elderDto, Elder.class);
        //todo : 手动定义时间
        elder.setCreateTime(DateUtils.getNowDate());
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(Elder.ELDER_STATUS_USE);
        elder.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        //新增Elder表
        elderMapper.insertElder(elder);
        //新增入住信息
        CheckIn checkIn = this.checkInBuilder(checkInApplyDto, elder, bed);
        checkInMapper.insertCheckIn(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = this.checkInConfigBuilder(checkInApplyDto, checkIn);
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
        //新增签约办理
        Contract contract = this.contractBuilder(checkInApplyDto, elder);
        contractMapper.insertContract(contract);
    }

    /**
     * 构建Contract对象
     *
     * @param checkInApplyDto
     * @param elder
     * @return
     */
    private Contract contractBuilder(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT/" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getFeeStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getFeeEndDate());
        contract.setStatus(Constants.STATUS_ENABLED);
        contract.setThirdPartyPhone(checkInApplyDto.getCheckInContractDto().getThirdPartyPhone());
        contract.setThirdPartyName(checkInApplyDto.getCheckInContractDto().getThirdPartyName());

        return contract;
    }

    /**
     * 构建CheckInConfig对象
     *
     * @param checkInApplyDto
     * @param checkIn
     * @return
     */
    private CheckInConfig checkInConfigBuilder(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());

        return checkInConfig;
    }

    /**
     * 构建CheckIn对象
     */
    private CheckIn checkInBuilder(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        return checkIn;
    }

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
